package com.gxz.filetest.controller;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = {"/files"})
public class FileController {

    private static final String FILE_DIRECTORY = "/data/"; // 设置你的文件目录路径

    @GetMapping("/{filename:.+}")
    public ResponseEntity<byte[]> serveFile(@PathVariable String filename) {
        try {
            Path file = Paths.get(FILE_DIRECTORY).resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());

            if (resource.exists() || resource.isReadable()) {
                byte[] bytes = Files.readAllBytes(file);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_PDF);
                // 下面的这行代码将Content-Disposition设置为inline，但如果省略这一行，默认也不会触发下载
                headers.set("Content-Disposition", "inline; filename=" + resource.getFilename());
                return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            } else {
                // 文件不存在或不可读时返回404
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            // 处理URL异常（这里只是简单地返回500，实际项目中你可能需要更详细的错误处理）
            return ResponseEntity.badRequest().build();
        }
    }

    private static final int NUM_FILES_TO_CREATE = 10000000; // 替换为你要创建的文件数量
    private static final String TEMP_FILE_PREFIX = "tempFile-";
    private static final String TEMP_FILE_SUFFIX = ".txt";
    private static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");


    @GetMapping("/load")
    public String load() throws InterruptedException, IOException {
        List<RandomAccessFile> fileHandles = new ArrayList<>();

        for (int i = 0; i < NUM_FILES_TO_CREATE; i++) {
            File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_SUFFIX, new File(TEMP_DIRECTORY));
            tempFile.deleteOnExit(); // 确保程序退出时删除临时文件
            RandomAccessFile fileHandle = new RandomAccessFile(tempFile, "rw");
            fileHandles.add(fileHandle);
            System.out.println("Created and opened file: " + tempFile.getAbsolutePath());
            if (i % 60000 == 0) {
                fileHandles.forEach(item -> {
                    try {
                        item.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }
        Thread.sleep(300000);
        fileHandles.forEach(item -> {
            try {
                item.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        return "保存成功";
    }

    @GetMapping("/loadFile")
    public String loadFile() throws InterruptedException {
        String path = FILE_DIRECTORY + "/logs/project_info-2024-03-13-{}.log";

        List<BufferedReader> fileReferences = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            String filePath = StrUtil.format(path, i);
            try {
                BufferedReader reader = new BufferedReader(new FileReader(filePath)); // 注意这里的i应该用于生成不同的文件名，但这里只是为了示例
                fileReferences.add(reader);

                log.info("Opened file: " + filePath);
            } catch (IOException e) {
                log.error("读取报错：", e);
            }
        }
        Thread.sleep(300000);
        fileReferences.forEach(item -> {
            try {
                item.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        return "保存成功";
    }

    @GetMapping("/copy")
    public String copyFile() throws InterruptedException {
        String path = FILE_DIRECTORY + "/logs/project_info-2024-03-13-{}.log";

        // 源文件路径
        Path sourcePath = Paths.get(StrUtil.format(path, 0));
        for (int i = 5; i < 100; i++) {
            // 目标文件路径
            Path destinationPath = Paths.get(StrUtil.format(path, i));

            try {
                // 使用Files.copy()方法复制文件
                // StandardCopyOption.REPLACE_EXISTING选项表示如果目标文件已存在，则替换它
                Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
                log.info("文件复制成功！" + destinationPath);
            } catch (IOException e) {
                // 处理异常，例如文件不存在或无法访问等
                e.printStackTrace();
            }
        }

        return "保存成功";
    }

}
